/**
 * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.restaurant.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.restaurant.entity.PurchaseCommodity;
import org.springblade.modules.restaurant.excel.PurchaseCommodityExcel;
import org.springblade.modules.restaurant.excel.PurchaseCommodityImportListener;
import org.springblade.modules.restaurant.service.IPurchaseCommodityService;
import org.springblade.modules.restaurant.vo.PurchaseCommodityVO;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 采购货物 控制器
 *
 * @author Blade
 * @since 2025-01-21
 */
@RestController
@AllArgsConstructor
@RequestMapping("/restaurant/purchasecommodity")
@Tag(name = "采购货物", description = "采购货物接口")
public class PurchaseCommodityController extends BladeController {

	private IPurchaseCommodityService purchaseCommodityService;

	// 根据分类获取商品
	@GetMapping("/listByCategory/{categoryId}")
	@Operation(summary = "根据分类获取商品", description = "根据分类获取商品")
	public R<List<PurchaseCommodity>> listByCategory(@PathVariable Long categoryId) {
		LambdaQueryWrapper<PurchaseCommodity> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(PurchaseCommodity::getCategoryId, categoryId);
		return R.data(purchaseCommodityService.list(wrapper));
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入purchaseCommodity")
	public R<PurchaseCommodity> detail(PurchaseCommodity purchaseCommodity) {
		PurchaseCommodity detail = purchaseCommodityService.getOne(Condition.getQueryWrapper(purchaseCommodity));
		return R.data(detail);
	}

	/**
	 * 分页 采购货物
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description = "传入purchaseCommodity")
	public R<IPage<PurchaseCommodity>> list(@ParameterObject PurchaseCommodity purchaseCommodity, @ParameterObject Query query) {

		LambdaQueryWrapper<PurchaseCommodity> wrapper = customizeQueryWrapper(purchaseCommodity);

		IPage<PurchaseCommodity> pages = purchaseCommodityService.page(Condition.getPage(query), wrapper);
		return R.data(pages);
	}


	/**
	 * 自定义分页 采购货物
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "分页", description = "传入purchaseCommodity")
	public R<IPage<PurchaseCommodityVO>> page(@ParameterObject PurchaseCommodityVO purchaseCommodity, @ParameterObject Query query) {
		IPage<PurchaseCommodityVO> pages = purchaseCommodityService.selectPurchaseCommodityPage(Condition.getPage(query), purchaseCommodity);
		return R.data(pages);
	}

	/**
	 * 新增 采购货物
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "新增", description = "传入purchaseCommodity")
	public R save(@Valid @RequestBody PurchaseCommodity purchaseCommodity) {
		// 计算价值
		if (ObjectUtil.isNotEmpty(purchaseCommodity.getReferencePrice()) && ObjectUtil.isNotEmpty(purchaseCommodity.getStockNumber())) {
			purchaseCommodity.setStockValue(purchaseCommodity.getReferencePrice().multiply(purchaseCommodity.getStockNumber()));
		}
		return R.status(purchaseCommodityService.save(purchaseCommodity));
	}

	/**
	 * 修改 采购货物
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "修改", description = "传入purchaseCommodity")
	public R update(@Valid @RequestBody PurchaseCommodity purchaseCommodity) {
		// 计算价值
		if (ObjectUtil.isNotEmpty(purchaseCommodity.getReferencePrice()) && ObjectUtil.isNotEmpty(purchaseCommodity.getStockNumber())) {
			purchaseCommodity.setStockValue(purchaseCommodity.getReferencePrice().multiply(purchaseCommodity.getStockNumber()));
		}
		return R.status(purchaseCommodityService.updateById(purchaseCommodity));
	}

	/**
	 * 新增或修改 采购货物
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "新增或修改", description = "传入purchaseCommodity")
	public R submit(@Valid @RequestBody PurchaseCommodity purchaseCommodity) {

		// 计算价值
		if (ObjectUtil.isNotEmpty(purchaseCommodity.getReferencePrice()) && ObjectUtil.isNotEmpty(purchaseCommodity.getStockNumber())) {
			purchaseCommodity.setStockValue(purchaseCommodity.getReferencePrice().multiply(purchaseCommodity.getStockNumber()));
		}

		return R.status(purchaseCommodityService.saveOrUpdate(purchaseCommodity));
	}


	/**
	 * 删除 采购货物
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "逻辑删除", description = "传入ids")
	public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		return R.status(purchaseCommodityService.deleteLogic(Func.toLongList(ids)));
	}

	// 导出库存
	@SneakyThrows
	@GetMapping("/export")
	@ApiOperationSupport(order = 8)
	@Operation(summary = "导出库存", description = "导出库存")
	public void export(PurchaseCommodityVO purchaseCommodityVO, HttpServletResponse response) {

		List<PurchaseCommodity> list = purchaseCommodityService.list(customizeQueryWrapper(purchaseCommodityVO)
			.orderByAsc(PurchaseCommodity::getSort));
		Integer isStock = purchaseCommodityVO.getIsStock();
		if (ObjectUtil.isNotEmpty(isStock)&& isStock == 1) {
			// stockNumber > 0 的商品
			list = list.stream().filter(item ->
				item.getStockNumber() != null && item.getStockNumber().compareTo(BigDecimal.ZERO) > 0
			).toList();
		}
		List<PurchaseCommodityExcel> excels = list.stream().map(item -> {
			PurchaseCommodityExcel excel = new PurchaseCommodityExcel();
			excel.setId(String.valueOf(item.getId()));
			excel.setCategoryName(item.getCategoryName());
			excel.setCommodityName(item.getCommodityName());
			excel.setStockNumber(item.getStockNumber() == null ? BigDecimal.ZERO : item.getStockNumber());
			excel.setStockUnit(StrUtil.isBlank(item.getStockUnit()) ? item.getUnit() : item.getStockUnit());
			excel.setReferencePrice(item.getReferencePrice() == null ? BigDecimal.ZERO : item.getReferencePrice());
			excel.setStockValue(item.getStockNumber() == null ? BigDecimal.ZERO : excel.getStockNumber().multiply(excel.getReferencePrice()));
			return excel;
		}).toList();

		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding(StandardCharsets.UTF_8.name());
		String fileName = URLEncoder.encode("库存盘点", StandardCharsets.UTF_8)
			+ "_" + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN);

		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		EasyExcel.write(response.getOutputStream(), PurchaseCommodityExcel.class).sheet("库存盘点").doWrite(excels);
	}

	// 导入库存
	@SneakyThrows
	@PostMapping("/import")
	@ApiOperationSupport(order = 9)
	@Operation(summary = "导入库存", description = "导入库存")
	public R importExcel(@RequestParam("file") MultipartFile file) {
		String filename = file.getOriginalFilename();
		if (StringUtil.isBlank(filename)) {
			throw new RuntimeException("请上传文件!");
		}
		if ((!StringUtil.endsWithIgnoreCase(filename, ".xls") && !StringUtil.endsWithIgnoreCase(filename, ".xlsx"))) {
			throw new RuntimeException("请上传正确的excel文件!");
		}
		InputStream inputStream;
		PurchaseCommodityImportListener importListener = new PurchaseCommodityImportListener(purchaseCommodityService);
		inputStream = new BufferedInputStream(file.getInputStream());
		ExcelReaderBuilder builder = EasyExcel.read(inputStream, PurchaseCommodityExcel.class, importListener);
		builder.doReadAll();
		return R.success("操作成功");
	}

	private LambdaQueryWrapper<PurchaseCommodity> customizeQueryWrapper(PurchaseCommodity purchaseCommodity) {
		return Wrappers.<PurchaseCommodity>lambdaQuery()
			.eq(ObjectUtil.isNotEmpty(purchaseCommodity.getCategoryId()), PurchaseCommodity::getCategoryId, purchaseCommodity.getCategoryId())
			.like(StrUtil.isNotBlank(purchaseCommodity.getCommodityName()), PurchaseCommodity::getCommodityName, purchaseCommodity.getCommodityName());
	}
}
